package com.dm.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 *
 */
public class JdbcCon_Pool {
    static List<String> strList = new ArrayList<>();

    private static DataSource dataSource;


    public static void initConnectionPool() throws Exception {
        ClassLoader cl = JdbcCon_Pool.class.getClassLoader();  // 得到classLoader 目的是找到项目目录的地址,并加载配置文件
        InputStream ins = cl.getResourceAsStream("druid.properties"); //读取配置文件,并加载到properties中
        Properties p = new Properties();
        //加载配置文件到p对象中
        p.load(ins);
        //用工厂方法, 创建数据源, 参数为配置文件
       dataSource = DruidDataSourceFactory.createDataSource(p);

    }


    public static void selectData() throws SQLException {
        //得到连接对象
        Connection connection = dataSource.getConnection();
        if (connection != null) {
            System.out.println("数据库连接成功");
        } else {
            System.out.println("数据库连接失败");
        }

        Statement stmt = null;
        try {
            for (int i = 0; i < 100; i++) {
                String query_sql = "select * from PRODUCT_CATEGORY";

                stmt = connection.createStatement();
                ResultSet rs1 = stmt.executeQuery(query_sql);
                while (rs1.next()) {
                    System.out.println(
                            rs1.getInt(1) + "," +
                                    rs1.getString(2)
                    );
                }
                Thread.sleep(2000);
            }
        } catch (SQLException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                connection.close();
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }



    public static void main(String[] args){


        try {
            initConnectionPool();
        } catch (Exception e) {
            System.out.println("initConnectionPool  fail");
            e.printStackTrace();
        }
        try {
        selectData();
        } catch (SQLException e) {
            System.out.println("selectData  selectData1");
            e.printStackTrace();
            try {
            selectData();
            } catch (SQLException e1) {
                System.out.println("selectData  selectData2");
                e1.printStackTrace();

            }
        }
    }





}
